/**
 * 获取广告ad
 */
function getAdEvent(eventType) {
    let option = tt.getStorageSync('options')
    let shareUserId = option.query.shareUserId;
    let mId = option.query.mId;
    // console.log("ad: " + eventType)
    // console.log(shareUserId, mId)
    let adId = tt.getStorageSync('ad_id');
    // adId = "";
    let openId = tt.getStorageSync('openId');
    if ((shareUserId == undefined || shareUserId == "") && (mId == undefined)) {
        console.log("no shareUserId and mId")
        return;
    }
    if (shareUserId != undefined && mId != undefined) {
        let goodsId = tt.getStorageSync('g_id');
        if (!goodsId) {
            goodsId = "0";
        }
        tt.request({
            url: 'https://es.tuiwa.com/dy_mini/rpt_ent',
            // url: 'http://localhost:9098/dy_mini/rpt_ent',
            header: {
                "content-type": "application/json"
            },
            method: 'POST',
            data: {
                s_u_i: shareUserId,
                m_i: mId,
                a_i: globalData.appId,
                u_i: tt.getStorageSync('openId'),
                e_n: eventType,
                e_t: Date.parse(new Date()),
                g_i: goodsId,
                ad_id: adId,
            },
            success: function(a) {
                console.log(eventType)
                if (eventType == 'getAd') {
                    tt.setStorageSync('ad_id', a.data.data);
                }

            },
            fail: function(t) {}
        });
    }
}
/**
 * 登陆 或者绑定微信
 */
function bindDyWx() {
    console.log("1111111111111")
    var e = this;
    tt.login({
        force: true,
        success: dd => {
            console.log(dd, "44444444");
            tt.setStorageSync('access_token', dd.code);
            tt.getSetting({
                success: function(res) {
                    tt.getUserInfo({
                        success: res => {
                            console.log("2222222222222")
                            tt.setStorageSync('userInfo', res.userInfo);
                            let userInfo = res.userInfo
                            let option = tt.getStorageSync('options')
                            if (option.query.shareUserId == '' || option.query.shareUserId == undefined) {
                                // console.log(option.query.shareUserId, " shareUserId  ")
                                option.query.shareUserId = 0
                            }
                            if (option.query.mId == '' || option.query.mId == undefined) {
                                option.query.mId = 0
                            }
                            // tt.setStorageSync('options', option);
                            if (option.query.bindFlag == 1 && option.query.wxId != '') {
                                tt.request({
                                    url: 'https://vs.tuiwa.com/dy_mini/bind_dy_wx',
                                    // url: 'http://localhost:9099/dy_mini/bind_dy_wx',
                                    header: {
                                        "content-type": "application/json"
                                    },
                                    method: 'POST',
                                    data: {
                                        wxId: option.query.wxId,
                                        token: dd.code,
                                        avatarUrl: userInfo.avatarUrl,
                                        country: userInfo.country,
                                        nickName: userInfo.nickName,
                                        appId: globalData.appId,
                                    },
                                    success: function(a) {
                                        console.log(a, 'a的值');
                                        // data
                                        tt.setStorageSync('openId', a.data.data.dyUser.openid);
                                        tt.setStorageSync('dyUser', a.data.data.dyUser);
                                        //3 获取广告id
                                        if (!tt.getStorageSync("ad_id")) {
                                            getAdEvent('getAd');
                                        }
                                    },
                                    fail: function(t) {}
                                });
                            } else {
                                tt.request({
                                    url: 'https://vs.tuiwa.com/dy_mini/dy_user_login',
                                    // url: 'http://localhost:9099/dy_mini/dy_user_login',
                                    header: {
                                        "content-type": "application/json"
                                    },
                                    method: 'POST',
                                    data: {
                                        token: dd.code,
                                        appId: globalData.appId,
                                    },
                                    success: function(a) {
                                        console.log(a.data.data.dyUser.openid, "openid")
                                        if (a.data.data != undefined) {
                                            tt.setStorageSync('openId', a.data.data.dyUser.openid);
                                            tt.setStorageSync('dyUser', a.data.data.dyUser);
                                            //3 获取广告id
                                            console.log(!tt.getStorageSync("ad_id"))
                                            if (!tt.getStorageSync("ad_id")) {
                                                getAdEvent('getAd');
                                            }
                                        }
                                    },
                                    fail: function(t) {}
                                });
                            }
                        },
                        fail: function(e) {
                            tt.showModal({
                                title: "获取用户信息失败",
                                content: "小程序请求获取用户基础信息。请允许后才能通过广告获取道具",
                                success(res) {
                                    if (res.confirm) {
                                        tt.openSetting()
                                    } else if (res.cancel) {
                                        console.log("cancel, cold");
                                    } else {
                                        // what happend?
                                    }
                                },
                                fail(res) {
                                    console.log(`showModal调用失败`);
                                },
                            });
                        }
                    })
                },
                fail: error => {
                    console.log(error, "3333")
                }
            })
        }
    })
}
// -------------------------------------------------------------------------------
var globalData = {
    appId: "tt0ae47c5995df61bd", //tt0bd47d6994ef2f05  ttd04ca6f14f77456c tt0ae47c5995df61bd
    videoAd: tt.createRewardedVideoAd({
        adUnitId: '2fkn8630ing114b667' //orrxh9hrph3v00axvx  981bhb527j29p74tco 2fkn8630ing114b667
    }),
    currentPage: Object,
}
if (globalData.videoAd) {
    // console.log(globalData.videoAd, "0000000");
    // onClose只监听一次
    globalData.videoAd.onClose(res => {
        if (res.isEnded) {
            getAdEvent("videoEnd");
            // 实现子子页面的closeAdFunction与cancelAdFunction方法
            console.log(globalData.currentPage)
            globalData.currentPage.closeAdFunction()
        } else {
            globalData.currentPage.cancelAdFunction()
        }
    })
}

function playAd() {
    let videoAd1 = globalData.videoAd
    console.log(globalData.videoAd)
    if (!globalData.videoAd) {
        // onClose只监听一次
        tt.showModal({
            title: "视频加载错误",
            content: "视频加载失败。请退出重试",
            showCancel: false,
        });
    }
    // 照抄的官方例子
    videoAd1
        .show()
        .then(() => {
            console.log("广告显示成功");
            getAdEvent("videoStart")
        })
        .catch((err) => {
            console.log("广告组件出现问题", err);
            // 可以手动加载一次
            videoAd1.load().then(() => {
                console.log("手动加载成功");
                // 加载成功后需要再显示广告
                return videoAd1.show();
            });
        });
}

function auth() {
    tt.authorize({
        scope: "scope.writePhotosAlbum",
        success: (res) => {
            // tt.showToast({ title: "相册授权成功" });
            // console.log('授权相册成功')
        },
        fail: (err) => {
            console.log("authorize fail", err);
            tt.showModal({
                title: "授权出错",
                content: err.errMsg,
                showCancel: false,
            });
        },
    });
}

exports.playAd = playAd;
exports.getAdEvent = getAdEvent;
exports.bindDyWx = bindDyWx;
exports.globalData = globalData;
exports.auth = auth;